Java Overriding vs Overloading: The Two "Changes" of Methods That Must Be Distinguished Clearly
Method overloading and overriding are important features in Java, which beginners tend to confuse. Their core differences are as follows: **Method Overloading**: Within the same class, methods share the same name but have different parameter lists (different parameter types, quantities, or order). Return values, modifiers and other details can vary. Its purpose is to provide multiple parameter processing modes in the same class (for example, the `add` method of a calculator supports adding different numbers of parameters). Only the parameter list determines overloading; different return values do not count as overloading. **Method Overriding**: It refers to the re-implementation of a parent class method by a subclass. The requirements are that the method name and parameter list must be exactly the same, the return type must be a subclass of the parent class's return type, and the access permission must not be lower than that of the parent class. Its purpose is for subclasses to extend the functions of the parent class (for example, a Dog class overrrows the animal's bark method). Static methods cannot be overridden (they can only be hidden). **Core Differences**: Overloading depends on different parameters (within the same class), while overriding depends on inheritance (with the same parameter list). Remember: Overloading means "changing parameters", while overriding means "changing the implementation".
Read MoreJava super Keyword: Calling Parent Class in Inheritance, Must-Know
`super` is a keyword in Java used to access a parent class's members from a subclass, with the core role of connecting the subclass and the parent class. **1. Calling the parent class constructor**: The subclass constructor by default first calls the parent class's no-argument constructor (`super()`). If the parent class has no no-argument constructor or a parameterized constructor needs to be called, `super(parameters)` must be explicitly used and **must be placed on the first line of the subclass constructor**, otherwise a compilation error will occur. **2. Accessing parent class member variables with the same name**: When a subclass variable has the same name as a parent class variable, the subclass variable is accessed by default. Using `super.variableName` explicitly accesses the parent class variable. **3. Calling the parent class's overridden method**: After a subclass overrides a parent class method, the subclass method is called by default. Using `super.methodName()` calls the parent class's overridden method. **Notes**: `super` cannot be used in static methods; `super()` must be on the first line of the subclass constructor; `this()` and `super()` cannot be used simultaneously in a constructor. Mastering `super` enables clear control over a subclass's access to a parent class's members and is key to understanding Java inheritance.
Read More